import React, { Component, useMemo, useRef, useCallback } from "react";
import "./index.less";
import PropTypes from "prop-types";
import { removeNullProp } from "../../tool/objectUtil";

const ScrollView = ({ direction, children, width, height, showBar }) => {
  const containerRef = useRef(null);

  // 根据属性得到容器样式
  const containerStyle = useMemo(() => {
    let style = { width, height, paddingBottom: "10px" };
    removeNullProp(style);
    return style;
  }, [width, height, showBar]);

  const handleContainerScroll = useCallback(
    () => () => {
      if (!showBar) return;
      let container = containerRef.current;
      let view = container.querySelector(".b-scroll-view");
      let bar = container.querySelector(".b-scroll-view__bar");
      let bar_light = container.querySelector(".b-scroll-view__bar-light");
      //得到容器滚动距离，相对于整个内容长度的比例
      let ratio = view.scrollLeft / (view.scrollWidth - container.clientWidth);
      //将这个比例和bar的长度相乘，得出bar的距左距离
      bar_light.style.left =
        Math.ceil(ratio * (bar.clientWidth - bar_light.clientWidth)) + "px";
    },
    [showBar]
  );

  return (
    <div className="b-scroll-container" ref={containerRef}>
      <div
        className={`b-scroll-view ${
          direction === "vertical"
            ? "b-scroll-view--vertical"
            : "b-scroll-view--horizontal"
        }`}
        style={containerStyle}
        onScroll={handleContainerScroll()}
      >
        {children}
      </div>
      {showBar ? (
        <div className="b-scroll-view__bar">
          <div className="b-scroll-view__bar-light"></div>
        </div>
      ) : null}
    </div>
  );
};

ScrollView.propTypes = {
  direction: PropTypes.string,
  width: PropTypes.string,
  height: PropTypes.string,
  showBar: PropTypes.bool,
};

ScrollView.defaultProps = {
  width: "100w",
  direction: "horizontal",
  showBar: false,
};

export default React.memo(ScrollView);
